home *** CD-ROM | disk | FTP | other *** search
/ Mac-Source 1994 July / Mac-Source_July_1994.iso / C and C++ / Text⁄Files / macgzip_02-src / gzip.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-12-10  |  55.6 KB  |  1,906 lines  |  [TEXT/EDIT]

  1. /* gzip (GNU zip) -- compress files with zip algorithm and 'compress' interface
  2.  * Copyright (C) 1992-1993 Jean-loup Gailly
  3.  * The unzip code was written and put in the public domain by Mark Adler.
  4.  * Portions of the lzw code are derived from the public domain 'compress'
  5.  * written by Spencer Thomas, Joe Orost, James Woods, Jim McKie, Steve Davies,
  6.  * Ken Turkowski, Dave Mack and Peter Jannesen.
  7.  *
  8.  * See the license_msg below and the file COPYING for the software license.
  9.  * See the file algorithm.doc for the compression algorithms and file formats.
  10.  */
  11.  
  12. /*
  13.  * Modified:1993 by SPDsoft for MacGzip
  14.  *
  15.  */
  16.  
  17. static char  *license_msg[] = {
  18. "   Copyright (C) 1992-1993 Jean-loup Gailly",
  19. "   This program is free software; you can redistribute it and/or modify",
  20. "   it under the terms of the GNU General Public License as published by",
  21. "   the Free Software Foundation; either version 2, or (at your option)",
  22. "   any later version.",
  23. "",
  24. "   This program is distributed in the hope that it will be useful,",
  25. "   but WITHOUT ANY WARRANTY; without even the implied warranty of",
  26. "   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the",
  27. "   GNU General Public License for more details.",
  28. "",
  29. "   You should have received a copy of the GNU General Public License",
  30. "   along with this program; if not, write to the Free Software",
  31. "   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.",
  32. 0};
  33.  
  34. /* Compress files with zip algorithm and 'compress' interface.
  35.  * See usage() and help() functions below for all options.
  36.  * Outputs:
  37.  *        file.gz:   compressed file with same mode, owner, and utimes
  38.  *     or stdout with -c option or if stdin used as input.
  39.  * If the output file name had to be truncated, the original name is kept
  40.  * in the compressed file.
  41.  * On MSDOS, file.tmp -> file.tmz. On VMS, file.tmp -> file.tmp-gz.
  42.  *
  43.  * Using gz on MSDOS would create too many file name conflicts. For
  44.  * example, foo.txt -> foo.tgz (.tgz must be reserved as shorthand for
  45.  * tar.gz). Similarly, foo.dir and foo.doc would both be mapped to foo.dgz.
  46.  * I also considered 12345678.txt -> 12345txt.gz but this truncates the name
  47.  * too heavily. There is no ideal solution given the MSDOS 8+3 limitation. 
  48.  *
  49.  * For the meaning of all compilation flags, see comments in Makefile.in.
  50.  */
  51.  
  52. #ifdef RCSID
  53. static char rcsid[] = "$Id: gzip.c,v 0.24 1993/06/24 10:52:07 jloup Exp $";
  54. #endif
  55.  
  56. #include <ctype.h>
  57. #include <sys/types.h>
  58. #include <signal.h>
  59. #include <sys/stat.h>
  60. #include <errno.h>
  61.  
  62. #include "tailor.h"
  63. #include "gzip.h"
  64. #include "lzw.h"
  65. #include "revision.h"
  66. #include "getopt.h"
  67.  
  68.         /* configuration */
  69.         
  70. #ifdef MACOS
  71. #include "ThinkCPosix.h"
  72. char *PreferenceName=".gzip_prefs";
  73. /*#include <console.h>*/
  74. #include "MacErrors.h"
  75. #include "thePrefs.h"
  76. #include "SPDProg.h"
  77.  
  78. local void init_globals( void );
  79.  
  80. #endif /* MACOS */
  81.  
  82. #ifdef NO_TIME_H
  83. #  include <sys/time.h>
  84. #else
  85. #  include <time.h>
  86. #endif
  87.  
  88. #ifndef NO_FCNTL_H
  89. #  include <fcntl.h>
  90. #endif
  91.  
  92. #ifdef HAVE_UNISTD_H
  93. #  include <unistd.h>
  94. #endif
  95.  
  96. #if defined(STDC_HEADERS) || !defined(NO_STDLIB_H)
  97. #  include <stdlib.h>
  98. #else
  99.    extern int errno;
  100. #endif
  101.  
  102. #if defined(DIRENT)
  103. #  include <dirent.h>
  104.    typedef struct dirent dir_type;
  105. #  define NLENGTH(dirent) ((int)strlen((dirent)->d_name))
  106. #  define DIR_OPT "DIRENT"
  107. #else
  108. #  define NLENGTH(dirent) ((dirent)->d_namlen)
  109. #  ifdef SYSDIR
  110. #    include <sys/dir.h>
  111.      typedef struct direct dir_type;
  112. #    define DIR_OPT "SYSDIR"
  113. #  else
  114. #    ifdef SYSNDIR
  115. #      include <sys/ndir.h>
  116.        typedef struct direct dir_type;
  117. #      define DIR_OPT "SYSNDIR"
  118. #    else
  119. #      ifdef NDIR
  120. #        include <ndir.h>
  121.          typedef struct direct dir_type;
  122. #        define DIR_OPT "NDIR"
  123. #      else
  124. #        define NO_DIR
  125. #        define DIR_OPT "NO_DIR"
  126. #      endif
  127. #    endif
  128. #  endif
  129. #endif
  130.  
  131. #ifndef NO_UTIME
  132. #  ifndef NO_UTIME_H
  133. #    include <utime.h>
  134. #    define TIME_OPT "UTIME"
  135. #  else
  136. #    ifdef HAVE_SYS_UTIME_H
  137. #      include <sys/utime.h>
  138. #      define TIME_OPT "SYS_UTIME"
  139. #    else
  140.        struct utimbuf {
  141.          time_t actime;
  142.          time_t modtime;
  143.        };
  144. #      define TIME_OPT ""
  145. #    endif
  146. #  endif
  147. #else
  148. #  define TIME_OPT "NO_UTIME"
  149. #endif
  150.  
  151. #if !defined(S_ISDIR) && defined(S_IFDIR)
  152. #  define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
  153. #endif
  154. #if !defined(S_ISREG) && defined(S_IFREG)
  155. #  define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
  156. #endif
  157.  
  158. typedef RETSIGTYPE (*sig_type) OF((int));
  159.  
  160. #ifndef    O_BINARY
  161. #  define  O_BINARY  0  /* creation mode for open() */
  162. #endif
  163.  
  164. #ifndef O_CREAT
  165.    /* Pure BSD system? */
  166. #  include <sys/file.h>
  167. #  ifndef O_CREAT
  168. #    define O_CREAT FCREAT
  169. #  endif
  170. #  ifndef O_EXCL
  171. #    define O_EXCL FEXCL
  172. #  endif
  173. #endif
  174.  
  175. #ifndef S_IRUSR
  176. #  define S_IRUSR 0400
  177. #endif
  178. #ifndef S_IWUSR
  179. #  define S_IWUSR 0200
  180. #endif
  181. #define RW_USER (S_IRUSR | S_IWUSR)  /* creation mode for open() */
  182.  
  183. #ifndef MAX_PATH_LEN
  184. #  define MAX_PATH_LEN   1024 /* max pathname length */
  185. #endif
  186.  
  187. #ifndef SEEK_END
  188. #  define SEEK_END 2
  189. #endif
  190.  
  191. #ifdef NO_OFF_T
  192.   typedef long off_t;
  193.   off_t lseek OF((int fd, off_t offset, int whence));
  194. #endif
  195.  
  196. /* Separator for file name parts (see shorten_name()) */
  197. #ifdef NO_MULTIPLE_DOTS
  198. #  define PART_SEP "-"
  199. #else
  200. #  define PART_SEP "."
  201. #endif
  202.  
  203.         /* global buffers */
  204.  
  205. DECLARE(uch, inbuf,  INBUFSIZ +INBUF_EXTRA);
  206. DECLARE(uch, outbuf, OUTBUFSIZ+OUTBUF_EXTRA);
  207. DECLARE(ush, d_buf,  DIST_BUFSIZE);
  208. DECLARE(uch, window, 2L*WSIZE);
  209. #ifndef MAXSEG_64K
  210.     DECLARE(ush, tab_prefix, 1L<<BITS);
  211. #else
  212.     DECLARE(ush, tab_prefix0, 1L<<(BITS-1));
  213.     DECLARE(ush, tab_prefix1, 1L<<(BITS-1));
  214. #endif
  215.  
  216.         /* local variables */
  217.  
  218. int ascii = 0;        /* convert end-of-lines to local OS conventions */
  219. int to_stdout = 0;    /* output to stdout (-c) */
  220. int decompress = 0;   /* decompress (-d) */
  221. int force = 0;        /* don't ask questions, compress links (-f) */
  222. int no_name = -1;     /* don't save or restore the original file name */
  223. int no_time = -1;     /* don't save or restore the original file time */
  224. int recursive = 0;    /* recurse through directories (-r) */
  225. int list = 0;         /* list the file contents (-l) */
  226. int verbose = 0;      /* be verbose (-v) */
  227. int quiet = 0;        /* be very quiet (-q) */
  228. int do_lzw = 0;       /* generate output compatible with old compress (-Z) */
  229. int test = 0;         /* test .gz file integrity */
  230. int foreground;       /* set if program run in foreground */
  231. char *progname;       /* program name */
  232. int maxbits = BITS;   /* max bits per code for LZW */
  233. int method = DEFLATED;/* compression method */
  234. int level = 6;        /* compression level */
  235. int exit_code = OK;   /* program exit code */
  236. int save_orig_name;   /* set if original name must be saved */
  237. int last_member;      /* set for .zip and .Z files */
  238. int part_nb;          /* number of parts in .gz file */
  239. long time_stamp;      /* original time stamp (modification time) */
  240. long ifile_size;      /* input file size, -1 for devices (debug only) */
  241. char *env;            /* contents of GZIP env variable */
  242. char **args = NULL;   /* argv pointer if GZIP env variable defined */
  243. char z_suffix[MAX_SUFFIX+1]; /* default suffix (can be set with --suffix) */
  244. int  z_len;           /* strlen(z_suffix) */
  245.  
  246. long bytes_in;             /* number of input bytes */
  247. long bytes_out;            /* number of output bytes */
  248. long total_in = 0;         /* input bytes for all files */
  249. long total_out = 0;        /* output bytes for all files */
  250. char ifname[MAX_PATH_LEN]; /* input file name */
  251. char ofname[MAX_PATH_LEN]; /* output file name */
  252. int  remove_ofname = 0;       /* remove output file on error */
  253. struct stat istat;         /* status for input file */
  254. int  ifd;                  /* input file descriptor */
  255. int  ofd;                  /* output file descriptor */
  256. unsigned insize;           /* valid bytes in inbuf */
  257. unsigned inptr;            /* index of next byte to be processed in inbuf */
  258. unsigned outcnt;           /* bytes in output buffer */
  259.  
  260. struct option longopts[] =
  261. {
  262.  /* { name  has_arg  *flag  val } */
  263.     {"ascii",      0, 0, 'a'}, /* ascii text mode */
  264.     {"to-stdout",  0, 0, 'c'}, /* write output on standard output */
  265.     {"stdout",     0, 0, 'c'}, /* write output on standard output */
  266.     {"decompress", 0, 0, 'd'}, /* decompress */
  267.     {"uncompress", 0, 0, 'd'}, /* decompress */
  268.  /* {"encrypt",    0, 0, 'e'},    encrypt */
  269.     {"force",      0, 0, 'f'}, /* force overwrite of output file */
  270.     {"help",       0, 0, 'h'}, /* give help */
  271.  /* {"pkzip",      0, 0, 'k'},    force output in pkzip format */
  272.     {"list",       0, 0, 'l'}, /* list .gz file contents */
  273.     {"license",    0, 0, 'L'}, /* display software license */
  274.     {"no-name",    0, 0, 'n'}, /* don't save or restore original name & time */
  275.     {"name",       0, 0, 'N'}, /* save or restore original name & time */
  276.     {"quiet",      0, 0, 'q'}, /* quiet mode */
  277.     {"silent",     0, 0, 'q'}, /* quiet mode */
  278.     {"recursive",  0, 0, 'r'}, /* recurse through directories */
  279.     {"suffix",     1, 0, 'S'}, /* use given suffix instead of .gz */
  280.     {"test",       0, 0, 't'}, /* test compressed file integrity */
  281.     {"no-time",    0, 0, 'T'}, /* don't save or restore the time stamp */
  282.     {"verbose",    0, 0, 'v'}, /* verbose mode */
  283.     {"version",    0, 0, 'V'}, /* display version number */
  284.     {"fast",       0, 0, '1'}, /* compress faster */
  285.     {"best",       0, 0, '9'}, /* compress better */
  286.     {"lzw",        0, 0, 'Z'}, /* make output compatible with old compress */
  287.     {"bits",       1, 0, 'b'}, /* max number of bits per code (implies -Z) */
  288.     { 0, 0, 0, 0 }
  289. };
  290.  
  291. /* local functions */
  292.  
  293. local void usage        OF((void));
  294. local void help         OF((void));
  295. local void license      OF((void));
  296. local void version      OF((void));
  297. local void treat_stdin  OF((void));
  298. local void treat_file   OF((char *iname));
  299. local int create_outfile OF((void));
  300. local int  do_stat      OF((char *name, struct stat *sbuf));
  301. local char *get_suffix  OF((char *name));
  302. local int  get_istat    OF((char *iname, struct stat *sbuf));
  303. local int  make_ofname  OF((void));
  304. local int  same_file    OF((struct stat *stat1, struct stat *stat2));
  305. local int name_too_long OF((char *name, struct stat *statb));
  306. local void shorten_name  OF((char *name));
  307. local int  get_method   OF((int in));
  308. local void do_list      OF((int ifd, int method));
  309. local int  check_ofname OF((void));
  310. local void copy_stat    OF((struct stat *ifstat));
  311. local void do_exit      OF((int exitcode));
  312. /*      int main          OF((int argc, char **argv));*/
  313. int (*work) OF((int infile, int outfile)) = zip; /* function to call */
  314.  
  315. #ifndef NO_DIR
  316. local void treat_dir    OF((char *dir));
  317. #endif
  318. #ifndef NO_UTIME
  319. local void reset_times  OF((char *name, struct stat *statb));
  320. #endif
  321.  
  322. #define strequ(s1, s2) (strcmp((s1),(s2)) == 0)
  323.  
  324. /* ======================================================================== */
  325. local void usage()
  326. {
  327.     fprintf(stderr, "usage: %s [-%scdfhlLnN%stvV19] [-S suffix] [file ...]\n",
  328.         progname,
  329. #if O_BINARY
  330.         "a",
  331. #else
  332.         "",
  333. #endif
  334. #ifdef NO_DIR
  335.         ""
  336. #else
  337.         "r"
  338. #endif
  339.         );
  340. }
  341.  
  342. /* ======================================================================== */
  343. local void help()
  344. {
  345.     static char  *help_msg[] = {
  346. #if O_BINARY
  347.  " -a --ascii       ascii text; convert end-of-lines using local conventions",
  348. #endif
  349.  " -c --stdout      write on standard output, keep original files unchanged",
  350.  " -d --decompress  decompress",
  351. /* -e --encrypt     encrypt */
  352.  " -f --force       force overwrite of output file and compress links",
  353.  " -h --help        give this help",
  354. /* -k --pkzip       force output in pkzip format */
  355.  " -l --list        list compressed file contents",
  356.  " -L --license     display software license",
  357. #ifdef UNDOCUMENTED
  358.  " -m --no-time     do not save or restore the original modification time",
  359.  " -M --time        save or restore the original modification time",
  360. #endif
  361.  " -n --no-name     do not save or restore the original name and time stamp",
  362.  " -N --name        save or restore the original name and time stamp",
  363.  " -q --quiet       suppress all warnings",
  364. #ifndef NO_DIR
  365.  " -r --recursive   operate recursively on directories",
  366. #endif
  367.  " -S .suf  --suffix .suf     use suffix .suf on compressed files",
  368.  " -t --test        test compressed file integrity",
  369.  " -v --verbose     verbose mode",
  370.  " -V --version     display version number",
  371.  " -1 --fast        compress faster",
  372.  " -9 --best        compress better",
  373. #ifdef LZW
  374.  " -Z --lzw         produce output compatible with old compress",
  375.  " -b --bits maxbits   max number of bits per code (implies -Z)",
  376. #endif
  377.  " file...          files to (de)compress. If none given, use standard input.",
  378.   0};
  379.     char **p = help_msg;
  380.  
  381.     fprintf(stderr,"%s %s (%s)\n", progname, VERSION, REVDATE);
  382.     usage();
  383.     while (*p) fprintf(stderr, "%s\n", *p++);
  384. }
  385.  
  386. /* ======================================================================== */
  387. local void license()
  388. {
  389.     char **p = license_msg;
  390.  
  391.     fprintf(stderr,"%s %s (%s)\n", progname, VERSION, REVDATE);
  392.     while (*p) fprintf(stderr, "%s\n", *p++);
  393. }
  394.  
  395. /* ======================================================================== */
  396. local void version()
  397. {
  398.     fprintf(stderr,"%s %s (%s)\n", progname, VERSION, REVDATE);
  399.  
  400.     fprintf(stderr, "Compilation options:\n%s %s ", DIR_OPT, TIME_OPT);
  401. #ifdef STDC_HEADERS
  402.     fprintf(stderr, "STDC_HEADERS ");
  403. #endif
  404. #ifdef HAVE_UNISTD_H
  405.     fprintf(stderr, "HAVE_UNISTD_H ");
  406. #endif
  407. #ifdef NO_MEMORY_H
  408.     fprintf(stderr, "NO_MEMORY_H ");
  409. #endif
  410. #ifdef NO_STRING_H
  411.     fprintf(stderr, "NO_STRING_H ");
  412. #endif
  413. #ifdef NO_SYMLINK
  414.     fprintf(stderr, "NO_SYMLINK ");
  415. #endif
  416. #ifdef NO_MULTIPLE_DOTS
  417.     fprintf(stderr, "NO_MULTIPLE_DOTS ");
  418. #endif
  419. #ifdef NO_CHOWN
  420.     fprintf(stderr, "NO_CHOWN ");
  421. #endif
  422. #ifdef PROTO
  423.     fprintf(stderr, "PROTO ");
  424. #endif
  425. #ifdef ASMV
  426.     fprintf(stderr, "ASMV ");
  427. #endif
  428. #ifdef DEBUG
  429.     fprintf(stderr, "DEBUG ");
  430. #endif
  431. #ifdef DYN_ALLOC
  432.     fprintf(stderr, "DYN_ALLOC ");
  433. #endif
  434. #ifdef MAXSEG_64K
  435.     fprintf(stderr, "MAXSEG_64K");
  436. #endif
  437.     fprintf(stderr, "\n");
  438. }
  439.  
  440. /* ======================================================================== */
  441. int gzip_main (argc, argv)
  442.     int argc;
  443.     char **argv;
  444. {
  445.     int file_count;     /* number of files to precess */
  446.     int proglen;        /* length of progname */
  447.     int optc;           /* current option */
  448.  
  449. #ifdef MACOS
  450. /*    argc = ccommand(&argv);*/
  451.     opterr=0;
  452.     init_globals();
  453. #endif
  454.     EXPAND(argc, argv); /* wild card expansion if necessary */
  455.  
  456. /*    progname = basename(argv[0]);*/
  457.     progname = argv[0];
  458.     proglen = strlen(progname);
  459.  
  460.     /* Suppress .exe for MSDOS, OS/2 and VMS: */
  461.     if (proglen > 4 && strequ(progname+proglen-4, ".exe")) {
  462.         progname[proglen-4] = '\0';
  463.     }
  464.  
  465.     /* Add options in GZIP environment variable if there is one */
  466.     env = add_envopt(&argc, &argv, OPTIONS_VAR);
  467.     if (env != NULL) args = argv;
  468.  
  469.     foreground = signal(SIGINT, SIG_IGN) != SIG_IGN;
  470.     if (foreground) {
  471.     (void) signal (SIGINT, (sig_type)abort_gzip);
  472.     }
  473. #ifdef SIGTERM
  474.     if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
  475.     (void) signal(SIGTERM, (sig_type)abort_gzip);
  476.     }
  477. #endif
  478. #ifdef SIGHUP
  479.     if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
  480.     (void) signal(SIGHUP,  (sig_type)abort_gzip);
  481.     }
  482. #endif
  483.  
  484. #ifndef GNU_STANDARD
  485.     /* For compatibility with old compress, use program name as an option.
  486.      * If you compile with -DGNU_STANDARD, this program will behave as
  487.      * gzip even if it is invoked under the name gunzip or zcat.
  488.      *
  489.      * Systems which do not support links can still use -d or -dc.
  490.      * Ignore an .exe extension for MSDOS, OS/2 and VMS.
  491.      */
  492.     if (  strncmp(progname, "un",  2) == 0     /* ungzip, uncompress */
  493.        || strncmp(progname, "gun", 3) == 0) {  /* gunzip */
  494.     decompress = 1;
  495.     } else if (strequ(progname+1, "cat")       /* zcat, pcat, gcat */
  496.         || strequ(progname, "gzcat")) {    /* gzcat */
  497.     decompress = to_stdout = 1;
  498.     }
  499. #endif
  500.  
  501.     strncpy(z_suffix, Z_SUFFIX, sizeof(z_suffix)-1);
  502.     z_len = strlen(z_suffix);
  503.  
  504.     while ((optc = getopt_long (argc, argv, "ab:cdfhH?lLmMnNqrS:tvVZ123456789",
  505.                 longopts, (int *)0)) != EOF) {
  506.     switch (optc) {
  507.         case 'a':
  508.             ascii = 1; break;
  509.     case 'b':
  510.         maxbits = atoi(optarg);
  511.         break;
  512.     case 'c':
  513.         to_stdout = 1; break;
  514.     case 'd':
  515.         decompress = 1; break;
  516.     case 'f':
  517.         force++; break;
  518.     case 'h': case 'H': case '?':
  519.         help(); do_exit(OK); break;
  520.     case 'l':
  521.         list = decompress = to_stdout = 1; break;
  522.     case 'L':
  523.         license(); do_exit(OK); break;
  524.     case 'm': /* undocumented, may change later */
  525.         no_time = 1; break;
  526.     case 'M': /* undocumented, may change later */
  527.         no_time = 0; break;
  528.     case 'n':
  529.         no_name = no_time = 1; break;
  530.     case 'N':
  531.         no_name = no_time = 0; break;
  532.     case 'q':
  533.         quiet = 1; verbose = 0; break;
  534.     case 'r':
  535. #ifdef NO_DIR
  536.         fprintf(stderr, "%s: -r not supported on this system\n", progname);
  537.         usage();
  538.         do_exit(ERROR); break;
  539. #else
  540.         recursive = 1; break;
  541. #endif
  542.     case 'S':
  543. #ifdef NO_MULTIPLE_DOTS
  544.             if (*optarg == '.') optarg++;
  545. #endif
  546.             z_len = strlen(optarg);
  547.             strcpy(z_suffix, optarg);
  548.             break;
  549.     case 't':
  550.         test = decompress = to_stdout = 1;
  551.         break;
  552.     case 'v':
  553.         verbose++; quiet = 0; break;
  554.     case 'V':
  555.         version(); do_exit(OK); break;
  556.     case 'Z':
  557. #ifdef LZW
  558.         do_lzw = 1; break;
  559. #else
  560.         fprintf(stderr, "%s: -Z not supported in this version\n",
  561.             progname);
  562.         usage();
  563.         do_exit(ERROR); break;
  564. #endif
  565.     case '1':  case '2':  case '3':  case '4':
  566.     case '5':  case '6':  case '7':  case '8':  case '9':
  567.         level = optc - '0';
  568.         break;
  569.     default:
  570.         /* Error message already emitted by getopt_long. */
  571.         usage();
  572.         do_exit(ERROR);
  573.     }
  574.     } /* loop on all arguments */
  575.  
  576.     /* By default, save name and timestamp on compression but do not
  577.      * restore them on decompression.
  578.      */
  579.     if (no_time < 0) no_time = decompress;
  580.     if (no_name < 0) no_name = decompress;
  581.  
  582.     file_count = argc - optind;
  583.  
  584. #if O_BINARY
  585. #else
  586.     if (ascii && !quiet) {
  587.     fprintf(stderr, "%s: option --ascii ignored on this system\n",
  588.         progname);
  589.     }
  590. #endif
  591.     if ((z_len == 0 && !decompress) || z_len > MAX_SUFFIX) {
  592.         sprintf(strerr, "incorrect suffix '%s'", optarg);
  593.         Calert(strerr);
  594.         do_exit(ERROR);
  595.     }
  596.     if (do_lzw && !decompress) work = lzw;
  597.  
  598.     /* Allocate all global buffers (for DYN_ALLOC option) */
  599.     ALLOC(uch, inbuf,  INBUFSIZ +INBUF_EXTRA);
  600.     ALLOC(uch, outbuf, OUTBUFSIZ+OUTBUF_EXTRA);
  601.     ALLOC(ush, d_buf,  DIST_BUFSIZE);
  602.     ALLOC(uch, window, 2L*WSIZE);
  603. #ifndef MAXSEG_64K
  604.     ALLOC(ush, tab_prefix, 1L<<BITS);
  605. #else
  606.     ALLOC(ush, tab_prefix0, 1L<<(BITS-1));
  607.     ALLOC(ush, tab_prefix1, 1L<<(BITS-1));
  608. #endif
  609.  
  610.     /* And get to work */
  611.     if (file_count != 0) {
  612.     if (to_stdout && !test && !list && (!decompress || !ascii)) {
  613.         SET_BINARY_MODE(fileno(stdout));
  614.     }
  615.         while (optind < argc) {
  616.         treat_file(argv[optind++]);
  617.     }
  618.     } else {  /* Standard input */
  619.     treat_stdin();
  620.     }
  621.     if (list && !quiet && file_count > 1) {
  622.     do_list(-1, -1); /* print totals */
  623.     }
  624.     do_exit(exit_code);
  625.     return exit_code; /* just to avoid lint warning */
  626. }
  627.  
  628. /* ========================================================================
  629.  * Compress or decompress stdin
  630.  */
  631. local void treat_stdin()
  632. {
  633.     if (!force && !list &&
  634.     isatty(fileno((FILE *)(decompress ? stdin : stdout)))) {
  635.     /* Do not send compressed data to the terminal or read it from
  636.      * the terminal. We get here when user invoked the program
  637.      * without parameters, so be helpful. According to the GNU standards:
  638.      *
  639.      *   If there is one behavior you think is most useful when the output
  640.      *   is to a terminal, and another that you think is most useful when
  641.      *   the output is a file or a pipe, then it is usually best to make
  642.      *   the default behavior the one that is useful with output to a
  643.      *   terminal, and have an option for the other behavior.
  644.      *
  645.      * Here we use the --force option to get the other behavior.
  646.      */
  647.     fprintf(stderr,
  648.     "%s: compressed data not %s a terminal. Use -f to force %scompression.\n",
  649.         progname, decompress ? "read from" : "written to",
  650.         decompress ? "de" : "");
  651.     fprintf(stderr,"For help, type: %s -h\n", progname);
  652.     do_exit(ERROR);
  653.     }
  654.  
  655.     if (decompress || !ascii) {
  656.     SET_BINARY_MODE(fileno(stdin));
  657.     }
  658.     if (!test && !list && (!decompress || !ascii)) {
  659.     SET_BINARY_MODE(fileno(stdout));
  660.     }
  661.     strcpy(ifname, "stdin");
  662.     strcpy(ofname, "stdout");
  663.  
  664.     /* Get the time stamp on the input file. */
  665.     time_stamp = 0; /* time unknown by default */
  666.  
  667. #ifndef NO_STDIN_FSTAT
  668.     if (list || !no_time) {
  669.     if (fstat(fileno(stdin), &istat) != 0) {
  670.         error("fstat(stdin)");
  671.     }
  672. # ifdef NO_PIPE_TIMESTAMP
  673.     if (S_ISREG(istat.st_mode))
  674. # endif
  675.         time_stamp = istat.st_mtime;
  676.     }
  677. #endif /* NO_STDIN_FSTAT */
  678.  
  679.     ifile_size = -1L; /* convention for unknown size */
  680.  
  681.     clear_bufs(); /* clear input and output buffers */
  682.     to_stdout = 1;
  683.     part_nb = 0;
  684.  
  685.     if (decompress) {
  686.     method = get_method(ifd);
  687.     if (method < 0) {
  688.         do_exit(exit_code); /* error message already emitted */
  689.     }
  690.     }
  691.     if (list) {
  692.         do_list(ifd, method);
  693.         return;
  694.     }
  695.  
  696.     /* Actually do the compression/decompression. Loop over zipped members.
  697.      */
  698.     for (;;) {
  699.     if ((*work)(fileno(stdin), fileno(stdout)) != OK) return;
  700.  
  701.     if (!decompress || last_member || inptr == insize) break;
  702.     /* end of file */
  703.  
  704.     method = get_method(ifd);
  705.     if (method < 0) return; /* error message already emitted */
  706.     bytes_out = 0;            /* required for length check */
  707.     }
  708.  
  709.     if (verbose) {
  710.     if (test) {
  711.         fprintf(stderr, " OK\n");
  712.  
  713.     } else if (!decompress) {
  714.         display_ratio(bytes_in-(bytes_out-header_bytes), bytes_in, stderr);
  715.         fprintf(stderr, "\n");
  716. #ifdef DISPLAY_STDIN_RATIO
  717.     } else {
  718.         display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out,stderr);
  719.         fprintf(stderr, "\n");
  720. #endif
  721.     }
  722.     }
  723. }
  724.  
  725. /* ========================================================================
  726.  * Compress or decompress the given file
  727.  */
  728. local void treat_file(iname)
  729.     char *iname;
  730. {
  731.     /* Accept "-" as synonym for stdin */
  732.     if (strequ(iname, "-")) {
  733.     int cflag = to_stdout;
  734.     treat_stdin();
  735.     to_stdout = cflag;
  736.     return;
  737.     }
  738.  
  739.     /* Check if the input file is present, set ifname and istat: */
  740.     if (get_istat(iname, &istat) != OK) return;
  741.  
  742.     /* If the input name is that of a directory, recurse or ignore: */
  743.     if (S_ISDIR(istat.st_mode)) {
  744. #ifndef NO_DIR
  745.     if (recursive) {
  746.         struct stat st;
  747.         st = istat;
  748.         treat_dir(iname);
  749.         /* Warning: ifname is now garbage */
  750. #  ifndef NO_UTIME
  751.         reset_times (iname, &st);
  752. #  endif
  753.     } else
  754. #endif
  755.     WARN((strerr,"%s: %s is a directory -- ignored", progname, ifname));
  756.     return;
  757.     }
  758.     if (!S_ISREG(istat.st_mode)) {
  759.     WARN((strerr,
  760.           "%s: %s is not a directory or a regular file - ignored",
  761.           progname, ifname));
  762.     return;
  763.     }
  764.     if (istat.st_nlink > 1 && !to_stdout && !force) {
  765.     WARN((strerr, "%s: %s has %d other link%c -- unchanged",
  766.           progname, ifname,
  767.           (int)istat.st_nlink - 1, istat.st_nlink > 2 ? 's' : ' '));
  768.     return;
  769.     }
  770.  
  771.     ifile_size = istat.st_size;
  772.     time_stamp = no_time && !list ? 0 : istat.st_mtime;
  773.  
  774.     /* Generate output file name. For -r and (-t or -l), skip files
  775.      * without a valid gzip suffix (check done in make_ofname).
  776.      */
  777.     if (to_stdout && !list && !test) {
  778.     strcpy(ofname, "stdout");
  779.  
  780.     } else if (make_ofname() != OK) {
  781.     return;
  782.     }
  783.  
  784.     /* Open the input file and determine compression method. The mode
  785.      * parameter is ignored but required by some systems (VMS) and forbidden
  786.      * on other systems (MacOS).
  787.      */
  788.     ifd = OPEN(ifname, ascii && !decompress ? O_RDONLY : O_RDONLY | O_BINARY,
  789.            RW_USER);
  790.     if (ifd == -1) {
  791.     PError(ifname);
  792.     exit_code = ERROR;
  793.     return;
  794.     }
  795.     clear_bufs(); /* clear input and output buffers */
  796.     part_nb = 0;
  797.  
  798.     if (decompress) {
  799.     method = get_method(ifd); /* updates ofname if original given */
  800.     if (method < 0) {
  801.         close(ifd);
  802.         return;               /* error message already emitted */
  803.     }
  804.     }
  805.     if (list) {
  806.         do_list(ifd, method);
  807.         close(ifd);
  808.         return;
  809.     }
  810.  
  811.     /* If compressing to a file, check if ofname is not ambiguous
  812.      * because the operating system truncates names. Otherwise, generate
  813.      * a new ofname and save the original name in the compressed file.
  814.      */
  815.     if (to_stdout) {
  816.     ofd = fileno(stdout);
  817.     /* keep remove_ofname as zero */
  818.     } else {
  819.     if (create_outfile() != OK) return;
  820.  
  821.     if (!decompress && save_orig_name && !verbose && !quiet) {
  822.         
  823.         sprintf(strerr, "%s: %s compressed to %s",
  824.             progname, ifname, ofname);
  825.         
  826.         Calert(strerr);
  827.     }
  828.     }
  829.     /* Keep the name even if not truncated except with --no-name: */
  830.     if (!save_orig_name) save_orig_name = !no_name;
  831.  
  832.     if (verbose) {
  833.     fprintf(stderr, "%s:\t%s", ifname, (int)strlen(ifname) >= 15 ? 
  834.         "" : ((int)strlen(ifname) >= 7 ? "\t" : "\t\t"));
  835.     }
  836.  
  837.     /* Actually do the compression/decompression. Loop over zipped members.
  838.      */
  839.     for (;;) {
  840.     
  841. #ifdef _SPD_PROG_
  842.          sprintf(SPDpstr, "%s: %s -> %s",progname, ifname, ofname);
  843.          InitAnimatedCursors(kCalCursorRes);
  844.          InitMovableModal((unsigned long int) istat.st_size);
  845. #endif
  846.     
  847.     if ( (*work)(ifd, ofd) != OK) {
  848.         method = -1; /* force cleanup */
  849.         break;
  850.     }
  851.     
  852.     if (!decompress || last_member || inptr == insize) break;
  853.     /* end of file */
  854.  
  855.     method = get_method(ifd);
  856.     if (method < 0) break;    /* error message already emitted */
  857.     bytes_out = 0;            /* required for length check */
  858.     }
  859.  
  860.     close(ifd);
  861.     if (!to_stdout && close(ofd)) {
  862.     write_error();
  863.     }
  864.     if (method == -1) {
  865.     if (!to_stdout) unlink (ofname);
  866.     return;
  867.     }
  868.     /* Display statistics */
  869.     if(verbose) {
  870.     if (test) {
  871.         fprintf(stderr, " OK");
  872.     } else if (decompress) {
  873.         display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out,stderr);
  874.     } else {
  875.         display_ratio(bytes_in-(bytes_out-header_bytes), bytes_in, stderr);
  876.     }
  877.     if (!test && !to_stdout) {
  878.         fprintf(stderr, " -- replaced with %s", ofname);
  879.     }
  880.     fprintf(stderr, "\n");
  881.     }
  882.     /* Copy modes, times, ownership, and remove the input file */
  883.     if (!to_stdout) {
  884.     copy_stat(&istat);
  885.     }
  886. }
  887.  
  888. /* ========================================================================
  889.  * Create the output file. Return OK or ERROR.
  890.  * Try several times if necessary to avoid truncating the z_suffix. For
  891.  * example, do not create a compressed file of name "1234567890123."
  892.  * Sets save_orig_name to true if the file name has been truncated.
  893.  * IN assertions: the input file has already been open (ifd is set) and
  894.  *   ofname has already been updated if there was an original name.
  895.  * OUT assertions: ifd and ofd are closed in case of error.
  896.  */
  897. local int create_outfile()
  898. {
  899.     struct stat    ostat; /* stat for ofname */
  900.     int flags = O_WRONLY | O_CREAT | O_EXCL | O_BINARY;
  901.  
  902.     if (ascii && decompress) {
  903. #ifndef MACOS
  904.     flags &= ~O_BINARY; /* force ascii text mode */
  905. #else
  906.     flags = O_WRONLY | O_CREAT | O_EXCL | O_TEXT; /* SPDsoft */
  907. #endif /*MACOS*/
  908.     }
  909.     for (;;) {
  910.     /* Make sure that ofname is not an existing file */
  911.     if (check_ofname() != OK) {
  912.         close(ifd);
  913.         return ERROR;
  914.     }
  915.     /* Create the output file */
  916.     remove_ofname = 1;
  917.     ofd = OPEN(ofname, flags, RW_USER);
  918.     if (ofd == -1) {
  919.         PError(ofname);
  920.         close(ifd);
  921.         exit_code = ERROR;
  922.         return ERROR;
  923.     }
  924. #ifdef MACOS
  925.  
  926.     {
  927.     FInfo    vFInfo;
  928.     extern long GvRefNum;
  929.             
  930.             CtoPstr(ofname);
  931.             GetFInfo(ofname,GvRefNum,&vFInfo);
  932.             
  933.  
  934.             if (ascii && decompress)
  935.             {
  936.                 vFInfo.fdType='TEXT';
  937.                 PtoCstr(currPrefs.textcreator);
  938.                 vFInfo.fdCreator=*(OSType*)(currPrefs.textcreator);
  939.                 CtoPstr(currPrefs.textcreator);
  940.             }
  941.             else if ( decompress)
  942.             {
  943.                 vFInfo.fdType='\?\?\?\?';
  944.                 vFInfo.fdCreator='\?\?\?\?';
  945.             }
  946.             else
  947.             {
  948.                 vFInfo.fdType='Gzip';
  949.                 vFInfo.fdCreator='Gzip';
  950.             }
  951.             
  952.             SetFInfo(ofname,GvRefNum,&vFInfo);
  953.             PtoCstr(ofname);
  954.     }
  955.  
  956. #endif /* MACOS */
  957.  
  958.     /* Check for name truncation on new file (1234567890123.gz) */
  959. #ifdef NO_FSTAT
  960.     if (stat(ofname, &ostat) != 0) {
  961. #else
  962.     if (fstat(ofd, &ostat) != 0) {
  963. #endif
  964.         PError(ofname);
  965.         close(ifd); close(ofd);
  966.         unlink(ofname);
  967.         exit_code = ERROR;
  968.         return ERROR;
  969.     }
  970.     if (!name_too_long(ofname, &ostat)) return OK;
  971.  
  972.     if (decompress) {
  973.         /* name might be too long if an original name was saved */
  974.         WARN((strerr, "%s: %s: warning, name truncated",
  975.           progname, ofname));
  976.         return OK;
  977.     }
  978.     close(ofd);
  979.     unlink(ofname);
  980. #ifdef NO_MULTIPLE_DOTS
  981.     /* Should never happen, see check_ofname() */
  982.     sprintf(strerr, "%s: name too long", ofname);
  983.     Calert(strerr);
  984.     do_exit(ERROR);
  985. #endif
  986.     shorten_name(ofname);
  987.     }
  988. }
  989.  
  990. /* ========================================================================
  991.  * Use lstat if available, except for -c or -f. Use stat otherwise.
  992.  * This allows links when not removing the original file.
  993.  */
  994. local int do_stat(name, sbuf)
  995.     char *name;
  996.     struct stat *sbuf;
  997. {
  998.     errno = 0;
  999. #if (defined(S_IFLNK) || defined (S_ISLNK)) && !defined(NO_SYMLINK)
  1000.     if (!to_stdout && !force) {
  1001.     return lstat(name, sbuf);
  1002.     }
  1003. #endif
  1004.     return stat(name, sbuf);
  1005. }
  1006.  
  1007. /* ========================================================================
  1008.  * Return a pointer to the 'z' suffix of a file name, or NULL. For all
  1009.  * systems, ".gz", ".z", ".Z", ".taz", ".tgz", "-gz", "-z" and "_z" are
  1010.  * accepted suffixes, in addition to the value of the --suffix option.
  1011.  * ".tgz" is a useful convention for tar.z files on systems limited
  1012.  * to 3 characters extensions. On such systems, ".?z" and ".??z" are
  1013.  * also accepted suffixes. For Unix, we do not want to accept any
  1014.  * .??z suffix as indicating a compressed file; some people use .xyz
  1015.  * to denote volume data.
  1016.  *   On systems allowing multiple versions of the same file (such as VMS),
  1017.  * this function removes any version suffix in the given name.
  1018.  */
  1019. local char *get_suffix(name)
  1020.     char *name;
  1021. {
  1022.     int nlen, slen;
  1023.     char suffix[MAX_SUFFIX+3]; /* last chars of name, forced to lower case */
  1024.     static char *known_suffixes[] =
  1025.        {z_suffix, ".gz", ".z", ".taz", ".tgz", "-gz", "-z", "_z",
  1026. #ifdef MAX_EXT_CHARS
  1027.           "z",
  1028. #endif
  1029.           NULL};
  1030.     char **suf = known_suffixes;
  1031.  
  1032.     if (strequ(z_suffix, "z")) suf++; /* check long suffixes first */
  1033.  
  1034. #ifdef SUFFIX_SEP
  1035.     /* strip a version number from the file name */
  1036.     {
  1037.     char *v = strrchr(name, SUFFIX_SEP);
  1038.      if (v != NULL) *v = '\0';
  1039.     }
  1040. #endif
  1041.     nlen = strlen(name);
  1042.     if (nlen <= MAX_SUFFIX+2) {
  1043.         strcpy(suffix, name);
  1044.     } else {
  1045.         strcpy(suffix, name+nlen-MAX_SUFFIX-2);
  1046.     }
  1047.     strlwr(suffix);
  1048.     slen = strlen(suffix);
  1049.     do {
  1050.        int s = strlen(*suf);
  1051.        if (slen > s && suffix[slen-s-1] != PATH_SEP
  1052.            && strequ(suffix + slen - s, *suf)) {
  1053.            return name+nlen-s;
  1054.        }
  1055.     } while (*++suf != NULL);
  1056.  
  1057.     return NULL;
  1058. }
  1059.  
  1060.  
  1061. /* ========================================================================
  1062.  * Set ifname to the input file name (with a suffix appended if necessary)
  1063.  * and istat to its stats. For decompression, if no file exists with the
  1064.  * original name, try adding successively z_suffix, .gz, .z, -z and .Z.
  1065.  * For MSDOS, we try only z_suffix and z.
  1066.  * Return OK or ERROR.
  1067.  */
  1068. local int get_istat(iname, sbuf)
  1069.     char *iname;
  1070.     struct stat *sbuf;
  1071. {
  1072.     int ilen;  /* strlen(ifname) */
  1073.     static char *suffixes[] = {z_suffix, ".gz", ".z", "-z", ".Z", NULL};
  1074.     char **suf = suffixes;
  1075.     char *s;
  1076. #ifdef NO_MULTIPLE_DOTS
  1077.     char *dot; /* pointer to ifname extension, or NULL */
  1078. #endif
  1079.  
  1080.     strcpy(ifname, iname);
  1081.  
  1082.     /* If input file exists, return OK. */
  1083.     if (do_stat(ifname, sbuf) == 0) return OK;
  1084.  
  1085.     if (!decompress || errno != ENOENT) {
  1086.     PError(ifname);
  1087.     exit_code = ERROR;
  1088.     return ERROR;
  1089.     }
  1090.     /* file.ext doesn't exist, try adding a suffix (after removing any
  1091.      * version number for VMS).
  1092.      */
  1093.     s = get_suffix(ifname);
  1094.     if (s != NULL) {
  1095.     PError(ifname); /* ifname already has z suffix and does not exist */
  1096.     exit_code = ERROR;
  1097.     return ERROR;
  1098.     }
  1099. #ifdef NO_MULTIPLE_DOTS
  1100.     dot = strrchr(ifname, '.');
  1101.     if (dot == NULL) {
  1102.         strcat(ifname, ".");
  1103.         dot = strrchr(ifname, '.');
  1104.     }
  1105. #endif
  1106.     ilen = strlen(ifname);
  1107.     if (strequ(z_suffix, ".gz")) suf++;
  1108.  
  1109.     /* Search for all suffixes */
  1110.     do {
  1111.         s = *suf;
  1112. #ifdef NO_MULTIPLE_DOTS
  1113.         if (*s == '.') s++;
  1114. #endif
  1115. #ifdef MAX_EXT_CHARS
  1116.         strcpy(ifname, iname);
  1117.         /* Needed if the suffixes are not sorted by increasing length */
  1118.  
  1119.         if (*dot == '\0') strcpy(dot, ".");
  1120.         dot[MAX_EXT_CHARS+1-strlen(s)] = '\0';
  1121. #endif
  1122.         strcat(ifname, s);
  1123.         if (do_stat(ifname, sbuf) == 0) return OK;
  1124.     ifname[ilen] = '\0';
  1125.     } while (*++suf != NULL);
  1126.  
  1127.     /* No suffix found, complain using z_suffix: */
  1128. #ifdef MAX_EXT_CHARS
  1129.     strcpy(ifname, iname);
  1130.     if (*dot == '\0') strcpy(dot, ".");
  1131.     dot[MAX_EXT_CHARS+1-z_len] = '\0';
  1132. #endif
  1133.     strcat(ifname, z_suffix);
  1134.     PError(ifname);
  1135.     exit_code = ERROR;
  1136.     return ERROR;
  1137. }
  1138.  
  1139. /* ========================================================================
  1140.  * Generate ofname given ifname. Return OK, or WARNING if file must be skipped.
  1141.  * Sets save_orig_name to true if the file name has been truncated.
  1142.  */
  1143. local int make_ofname()
  1144. {
  1145.     char *suff;            /* ofname z suffix */
  1146.  
  1147.     strcpy(ofname, ifname);
  1148.     /* strip a version number if any and get the gzip suffix if present: */
  1149.     suff = get_suffix(ofname);
  1150.  
  1151.     if (decompress) {
  1152.     if (suff == NULL) {
  1153.         /* Whith -t or -l, try all files (even without .gz suffix)
  1154.          * except with -r (behave as with just -dr).
  1155.              */
  1156.             if (!recursive && (list || test)) return OK;
  1157.  
  1158.         /* Avoid annoying messages with -r */
  1159.         if (verbose || (!recursive && !quiet)) {
  1160.         WARN((strerr,"%s: %s: unknown suffix -- ignored",
  1161.               progname, ifname));
  1162.         }
  1163.         return WARNING;
  1164.     }
  1165.     /* Make a special case for .tgz and .taz: */
  1166.     strlwr(suff);
  1167.     if (strequ(suff, ".tgz") || strequ(suff, ".taz")) {
  1168.         strcpy(suff, ".tar");
  1169.     } else {
  1170.         *suff = '\0'; /* strip the z suffix */
  1171.     }
  1172.         /* ofname might be changed later if infile contains an original name */
  1173.  
  1174.     } else if (suff != NULL) {
  1175.     /* Avoid annoying messages with -r (see treat_dir()) */
  1176.     if (verbose || (!recursive && !quiet)) {
  1177.         sprintf(strerr, "%s already has %s suffix -- unchanged", ifname, suff);
  1178.         Calert(strerr);
  1179.     }
  1180.     if (exit_code == OK) exit_code = WARNING;
  1181.     return WARNING;
  1182.     } else {
  1183.         save_orig_name = 0;
  1184.  
  1185. #ifdef NO_MULTIPLE_DOTS
  1186.     suff = strrchr(ofname, '.');
  1187.     if (suff == NULL) {
  1188.             strcat(ofname, ".");
  1189. #  ifdef MAX_EXT_CHARS
  1190.         if (strequ(z_suffix, "z")) {
  1191.         strcat(ofname, "gz"); /* enough room */
  1192.         return OK;
  1193.         }
  1194.         /* On the Atari and some versions of MSDOS, name_too_long()
  1195.          * does not work correctly because of a bug in stat(). So we
  1196.          * must truncate here.
  1197.          */
  1198.         } else if (strlen(suff)-1 + z_len > MAX_SUFFIX) {
  1199.             suff[MAX_SUFFIX+1-z_len] = '\0';
  1200.             save_orig_name = 1;
  1201. #  endif
  1202.         }
  1203. #endif /* NO_MULTIPLE_DOTS */
  1204.     strcat(ofname, z_suffix);
  1205.  
  1206.     } /* decompress ? */
  1207.     return OK;
  1208. }
  1209.  
  1210.  
  1211. /* ========================================================================
  1212.  * Check the magic number of the input file and update ofname if an
  1213.  * original name was given and to_stdout is not set.
  1214.  * Return the compression method, -1 for error, -2 for warning.
  1215.  * Set inptr to the offset of the next byte to be processed.
  1216.  * Updates time_stamp if there is one and --no-time is not used.
  1217.  * This function may be called repeatedly for an input file consisting
  1218.  * of several contiguous gzip'ed members.
  1219.  * IN assertions: there is at least one remaining compressed member.
  1220.  *   If the member is a zip file, it must be the only one.
  1221.  */
  1222. local int get_method(in)
  1223.     int in;        /* input file descriptor */
  1224. {
  1225.     uch flags;     /* compression flags */
  1226.     char magic[2]; /* magic header */
  1227.     ulg stamp;     /* time stamp */
  1228.  
  1229.     /* If --force and --stdout, zcat == cat, so do not complain about
  1230.      * premature end of file: use try_byte instead of get_byte.
  1231.      */
  1232.     if (force && to_stdout) {
  1233.     magic[0] = (char)try_byte();
  1234.     magic[1] = (char)try_byte();
  1235.     /* If try_byte returned EOF, magic[1] == 0xff */
  1236.     } else {
  1237.     magic[0] = (char)get_byte();
  1238.     magic[1] = (char)get_byte();
  1239.     }
  1240.     method = -1;                 /* unknown yet */
  1241.     part_nb++;                   /* number of parts in gzip file */
  1242.     header_bytes = 0;
  1243.     last_member = RECORD_IO;
  1244.     /* assume multiple members in gzip file except for record oriented I/O */
  1245.  
  1246.     if (memcmp(magic, GZIP_MAGIC, 2) == 0
  1247.         || memcmp(magic, OLD_GZIP_MAGIC, 2) == 0) {
  1248.  
  1249.     method = (int)get_byte();
  1250.     if (method != DEFLATED) {
  1251.         sprintf(strerr,
  1252.             "%s: unknown method %d -- get newer version of gzip", ifname, method);
  1253.         Calert(strerr);
  1254.         exit_code = ERROR;
  1255.         return -1;
  1256.     }
  1257.     work = unzip;
  1258.     flags  = (uch)get_byte();
  1259.     if ((flags & ENCRYPTED) != 0) {
  1260.         sprintf(strerr,
  1261.             "%s is encrypted -- get newer version of gzip", ifname);
  1262.         Calert(strerr);
  1263.         exit_code = ERROR;
  1264.         return -1;
  1265.     }
  1266.     if ((flags & CONTINUATION) != 0) {
  1267.         sprintf(strerr,
  1268.        "%s is a a multi-part gzip file -- get newer version of gzip", ifname);
  1269.        Calert(strerr);
  1270.         exit_code = ERROR;
  1271.         if (force <= 1) return -1;
  1272.     }
  1273.     if ((flags & RESERVED) != 0) {
  1274.         sprintf(strerr,
  1275.             "%s has flags 0x%x -- get newer version of gzip", ifname, flags);
  1276.         Calert(strerr);
  1277.         exit_code = ERROR;
  1278.         if (force <= 1) return -1;
  1279.     }
  1280.     stamp  = (ulg)get_byte();
  1281.     stamp |= ((ulg)get_byte()) << 8;
  1282.     stamp |= ((ulg)get_byte()) << 16;
  1283.     stamp |= ((ulg)get_byte()) << 24;
  1284.     if (stamp != 0 && !no_time) time_stamp = stamp;
  1285.  
  1286.     (void)get_byte();  /* Ignore extra flags for the moment */
  1287.     (void)get_byte();  /* Ignore OS type for the moment */
  1288.  
  1289.     if ((flags & CONTINUATION) != 0) {
  1290.         unsigned part = (unsigned)get_byte();
  1291.         part |= ((unsigned)get_byte())<<8;
  1292.         if (verbose) {
  1293.         fprintf(stderr,"%s: %s: part number %u\n",
  1294.             progname, ifname, part);
  1295.         }
  1296.     }
  1297.     if ((flags & EXTRA_FIELD) != 0) {
  1298.         unsigned len = (unsigned)get_byte();
  1299.         len |= ((unsigned)get_byte())<<8;
  1300.         if (verbose) {
  1301.         fprintf(stderr,"%s: %s: extra field of %u bytes ignored\n",
  1302.             progname, ifname, len);
  1303.         }
  1304.         while (len--) (void)get_byte();
  1305.     }
  1306.  
  1307.     /* Get original file name if it was truncated */
  1308.     if ((flags & ORIG_NAME) != 0) {
  1309.         if (no_name || (to_stdout && !list) || part_nb > 1) {
  1310.         /* Discard the old name */
  1311.         char c; /* dummy used for NeXTstep 3.0 cc optimizer bug */
  1312.         do {c=get_byte();} while (c != 0);
  1313.         } else {
  1314.         /* Copy the base name. Keep a directory prefix intact. */
  1315.                 char *p = basename(ofname);
  1316.                 char *base = p;
  1317.         for (;;) {
  1318.             *p = (char)get_char();
  1319.             if (*p++ == '\0') break;
  1320.             if (p >= ofname+sizeof(ofname)) {
  1321.             error("corrupted input -- file name too large");
  1322.             }
  1323.         }
  1324.                 /* If necessary, adapt the name to local OS conventions: */
  1325.                 if (!list) {
  1326.                    MAKE_LEGAL_NAME(base);
  1327.            if (base) list=0; /* avoid warning about unused variable */
  1328.                 }
  1329.         } /* no_name || to_stdout */
  1330.     } /* ORIG_NAME */
  1331.  
  1332.     /* Discard file comment if any */
  1333.     if ((flags & COMMENT) != 0) {
  1334.         while (get_char() != 0) /* null */ ;
  1335.     }
  1336.     if (part_nb == 1) {
  1337.         header_bytes = inptr + 2*sizeof(long); /* include crc and size */
  1338.     }
  1339.  
  1340.     } else if (memcmp(magic, PKZIP_MAGIC, 2) == 0 && inptr == 2
  1341.         && memcmp((char*)inbuf, PKZIP_MAGIC, 4) == 0) {
  1342.     /* To simplify the code, we support a zip file when alone only.
  1343.          * We are thus guaranteed that the entire local header fits in inbuf.
  1344.          */
  1345.         inptr = 0;
  1346.     work = unzip;
  1347.     if (check_zipfile(in) != OK) return -1;
  1348.     /* check_zipfile may get ofname from the local header */
  1349.     last_member = 1;
  1350.  
  1351.     } else if (memcmp(magic, PACK_MAGIC, 2) == 0) {
  1352.     work = unpack;
  1353.     method = PACKED;
  1354.  
  1355.     } else if (memcmp(magic, LZW_MAGIC, 2) == 0) {
  1356.     work = unlzw;
  1357.     method = COMPRESSED;
  1358.     last_member = 1;
  1359.  
  1360.     } else if (memcmp(magic, LZH_MAGIC, 2) == 0) {
  1361.     work = unlzh;
  1362.     method = LZHED;
  1363.     last_member = 1;
  1364.  
  1365.     } else if (force && to_stdout && !list) { /* pass input unchanged */
  1366.     method = STORED;
  1367.     work = copy;
  1368.         inptr = 0;
  1369.     last_member = 1;
  1370.     }
  1371.     if (method >= 0) return method;
  1372.     if (part_nb == 1) {
  1373.     sprintf(strerr, "%s: not in gzip format", ifname);
  1374.     Calert(strerr);
  1375.     exit_code = ERROR;
  1376.     return -1;
  1377.     } else {
  1378.     WARN((strerr, "%s: %s: decompression OK, trailing garbage ignored",
  1379.           progname, ifname));
  1380.     return -2;
  1381.     }
  1382. }
  1383.  
  1384. /* ========================================================================
  1385.  * Display the characteristics of the compressed file.
  1386.  * If the given method is < 0, display the accumulated totals.
  1387.  * IN assertions: time_stamp, header_bytes and ifile_size are initialized.
  1388.  */
  1389. local void do_list(ifd, method)
  1390.     int ifd;     /* input file descriptor */
  1391.     int method;  /* compression method */
  1392. {
  1393.     ulg crc;  /* original crc */
  1394.     static int first_time = 1;
  1395.     static char* methods[MAX_METHODS] = {
  1396.         "store",  /* 0 */
  1397.         "compr",  /* 1 */
  1398.         "pack ",  /* 2 */
  1399.         "lzh  ",  /* 3 */
  1400.         "", "", "", "", /* 4 to 7 reserved */
  1401.         "defla"}; /* 8 */
  1402.     char *date;
  1403.  
  1404.     if (first_time && method >= 0) {
  1405.     first_time = 0;
  1406.     if (verbose)  {
  1407.         printf("method  crc     date  time  ");
  1408.     }
  1409.     if (!quiet) {
  1410.         printf("compressed  uncompr. ratio uncompressed_name\n");
  1411.     }
  1412.     } else if (method < 0) {
  1413.     if (total_in <= 0 || total_out <= 0) return;
  1414.     if (verbose) {
  1415.         printf("                            %9lu %9lu ",
  1416.            total_in, total_out);
  1417.     } else if (!quiet) {
  1418.         printf("%9ld %9ld ", total_in, total_out);
  1419.     }
  1420.     display_ratio(total_out-(total_in-header_bytes), total_out, stdout);
  1421.     /* header_bytes is not meaningful but used to ensure the same
  1422.      * ratio if there is a single file.
  1423.      */
  1424.     printf(" (totals)\n");
  1425.     return;
  1426.     }
  1427.     crc = (ulg)~0; /* unknown */
  1428.     bytes_out = -1L;
  1429.     bytes_in = ifile_size;
  1430.  
  1431. #if RECORD_IO == 0
  1432.     if (method == DEFLATED && !last_member) {
  1433.         /* Get the crc and uncompressed size for gzip'ed (not zip'ed) files.
  1434.          * If the lseek fails, we could use read() to get to the end, but
  1435.          * --list is used to get quick results.
  1436.          * Use "gunzip < foo.gz | wc -c" to get the uncompressed size if
  1437.          * you are not concerned about speed.
  1438.          */
  1439.         bytes_in = (long)lseek(ifd, (off_t)(-8), SEEK_END);
  1440.         if (bytes_in != -1L) {
  1441.             uch buf[8];
  1442.             bytes_in += 8L;
  1443.             if (read(ifd, (char*)buf, sizeof(buf)) != sizeof(buf)) {
  1444.                 read_error();
  1445.             }
  1446.             crc       = LG(buf);
  1447.         bytes_out = LG(buf+4);
  1448.     }
  1449.     }
  1450. #endif /* RECORD_IO */
  1451.     date = ctime((time_t*)&time_stamp) + 4; /* skip the day of the week */
  1452.     date[12] = '\0';               /* suppress the 1/100sec and the year */
  1453.     if (verbose) {
  1454.         printf("%5s %08lx %11s ", methods[method], crc, date);
  1455.     }
  1456.     printf("%9ld %9ld ", bytes_in, bytes_out);
  1457.     if (bytes_in  == -1L) {
  1458.     total_in = -1L;
  1459.     bytes_in = bytes_out = header_bytes = 0;
  1460.     } else if (total_in >= 0) {
  1461.     total_in  += bytes_in;
  1462.     }
  1463.     if (bytes_out == -1L) {
  1464.     total_out = -1L;
  1465.     bytes_in = bytes_out = header_bytes = 0;
  1466.     } else if (total_out >= 0) {
  1467.     total_out += bytes_out;
  1468.     }
  1469.     display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out, stdout);
  1470.     printf(" %s\n", ofname);
  1471. }
  1472.  
  1473. /* ========================================================================
  1474.  * Return true if the two stat structures correspond to the same file.
  1475.  */
  1476. local int same_file(stat1, stat2)
  1477.     struct stat *stat1;
  1478.     struct stat *stat2;
  1479. {
  1480.     return stat1->st_ino   == stat2->st_ino
  1481.     && stat1->st_dev   == stat2->st_dev
  1482. #ifdef NO_ST_INO
  1483.         /* Can't rely on st_ino and st_dev, use other fields: */
  1484.     && stat1->st_mode  == stat2->st_mode
  1485.     && stat1->st_uid   == stat2->st_uid
  1486.     && stat1->st_gid   == stat2->st_gid
  1487.     && stat1->st_size  == stat2->st_size
  1488.     && stat1->st_atime == stat2->st_atime
  1489.     && stat1->st_mtime == stat2->st_mtime
  1490.     && stat1->st_ctime == stat2->st_ctime
  1491. #endif
  1492.         ;
  1493. }
  1494.  
  1495. /* ========================================================================
  1496.  * Return true if a file name is ambiguous because the operating system
  1497.  * truncates file names.
  1498.  */
  1499. local int name_too_long(name, statb)
  1500.     char *name;           /* file name to check */
  1501.     struct stat *statb;   /* stat buf for this file name */
  1502. {
  1503.     int s = strlen(name);
  1504.     char c = name[s-1];
  1505.     struct stat    tstat; /* stat for truncated name */
  1506.     int res;
  1507.  
  1508.     tstat = *statb;      /* Just in case OS does not fill all fields */
  1509.     name[s-1] = '\0';
  1510.     res = stat(name, &tstat) == 0 && same_file(statb, &tstat);
  1511.     name[s-1] = c;
  1512.     Trace((stderr, " too_long(%s) => %d\n", name, res));
  1513.     return res;
  1514. }
  1515.  
  1516. /* ========================================================================
  1517.  * Shorten the given name by one character, or replace a .tar extension
  1518.  * with .tgz. Truncate the last part of the name which is longer than
  1519.  * MIN_PART characters: 1234.678.012.gz -> 123.678.012.gz. If the name
  1520.  * has only parts shorter than MIN_PART truncate the longest part.
  1521.  * For decompression, just remove the last character of the name.
  1522.  *
  1523.  * IN assertion: for compression, the suffix of the given name is z_suffix.
  1524.  */
  1525. local void shorten_name(name)
  1526.     char *name;
  1527. {
  1528.     int len;                 /* length of name without z_suffix */
  1529.     char *trunc = NULL;      /* character to be truncated */
  1530.     int plen;                /* current part length */
  1531.     int min_part = MIN_PART; /* current minimum part length */
  1532.     char *p;
  1533.  
  1534.     len = strlen(name);
  1535.     if (decompress) {
  1536.     if (len <= 1) error("name too short");
  1537.     name[len-1] = '\0';
  1538.     return;
  1539.     }
  1540.     p = get_suffix(name);
  1541.     if (p == NULL) error("can't recover suffix\n");
  1542.     *p = '\0';
  1543.     save_orig_name = 1;
  1544.  
  1545.     /* compress 1234567890.tar to 1234567890.tgz */
  1546.     if (len > 4 && strequ(p-4, ".tar")) {
  1547.     strcpy(p-4, ".tgz");
  1548.     return;
  1549.     }
  1550.     /* Try keeping short extensions intact:
  1551.      * 1234.678.012.gz -> 123.678.012.gz
  1552.      */
  1553.     do {
  1554.     p = strrchr(name, PATH_SEP);
  1555.     p = p ? p+1 : name;
  1556.     while (*p) {
  1557.         plen = strcspn(p, PART_SEP);
  1558.         p += plen;
  1559.         if (plen > min_part) trunc = p-1;
  1560.         if (*p) p++;
  1561.     }
  1562.     } while (trunc == NULL && --min_part != 0);
  1563.  
  1564.     if (trunc != NULL) {
  1565.     do {
  1566.         trunc[0] = trunc[1];
  1567.     } while (*trunc++);
  1568.     trunc--;
  1569.     } else {
  1570.     trunc = strrchr(name, PART_SEP[0]);
  1571.     if (trunc == NULL) error("internal error in shorten_name");
  1572.     if (trunc[1] == '\0') trunc--; /* force truncation */
  1573.     }
  1574.     strcpy(trunc, z_suffix);
  1575. }
  1576.  
  1577. /* ========================================================================
  1578.  * If compressing to a file, check if ofname is not ambiguous
  1579.  * because the operating system truncates names. Otherwise, generate
  1580.  * a new ofname and save the original name in the compressed file.
  1581.  * If the compressed file already exists, ask for confirmation.
  1582.  *    The check for name truncation is made dynamically, because different
  1583.  * file systems on the same OS might use different truncation rules (on SVR4
  1584.  * s5 truncates to 14 chars and ufs does not truncate).
  1585.  *    This function returns -1 if the file must be skipped, and
  1586.  * updates save_orig_name if necessary.
  1587.  * IN assertions: save_orig_name is already set if ofname has been
  1588.  * already truncated because of NO_MULTIPLE_DOTS. The input file has
  1589.  * already been open and istat is set.
  1590.  */
  1591. local int check_ofname()
  1592. {
  1593.     struct stat    ostat; /* stat for ofname */
  1594.  
  1595. #ifdef ENAMETOOLONG
  1596.     /* Check for strictly conforming Posix systems (which return ENAMETOOLONG
  1597.      * instead of silently truncating filenames).
  1598.      */
  1599.     errno = 0;
  1600.     while (stat(ofname, &ostat) != 0) {
  1601.         if (errno != ENAMETOOLONG) return 0; /* ofname does not exist */
  1602.     shorten_name(ofname);
  1603.     }
  1604. #else
  1605. #ifdef MACOS
  1606.     while (strlen(ofname) > 31) shorten_name(ofname);
  1607. #endif
  1608.     if (stat(ofname, &ostat) != 0) return 0;
  1609. #endif
  1610.     /* Check for name truncation on existing file. Do this even on systems
  1611.      * defining ENAMETOOLONG, because on most systems the strict Posix
  1612.      * behavior is disabled by default (silent name truncation allowed).
  1613.      */
  1614.     if (!decompress && name_too_long(ofname, &ostat)) {
  1615.     shorten_name(ofname);
  1616.     if (stat(ofname, &ostat) != 0) return 0;
  1617.     }
  1618.  
  1619.     /* Check that the input and output files are different (could be
  1620.      * the same by name truncation or links).
  1621.      */
  1622.     if (same_file(&istat, &ostat)) {
  1623.     if (strequ(ifname, ofname)) {
  1624.         sprintf(strerr, "%s: cannot %scompress onto itself",ifname, decompress ? "de" : "");
  1625.         Calert(strerr);
  1626.     } else {
  1627.         sprintf(strerr, "%s and %s are the same file", ifname, ofname);
  1628.         Calert(strerr);
  1629.     }
  1630.     exit_code = ERROR;
  1631.     return ERROR;
  1632.     }
  1633.     /* Ask permission to overwrite the existing file */
  1634. #ifndef MACOS
  1635.     if (!force) {
  1636.     char response[80];
  1637.     strcpy(response,"n");
  1638.     fprintf(stderr, "%s: %s already exists;", progname, ofname);
  1639.     if (foreground && isatty(fileno(stdin))) {
  1640.         fprintf(stderr, " do you wish to overwrite (y or n)? ");
  1641.         fflush(stderr);
  1642.         (void)fgets(response, sizeof(response)-1, stdin);
  1643.     }
  1644.     if (tolow(*response) != 'y') {
  1645.         fprintf(stderr, "\tnot overwritten\n");
  1646.         if (exit_code == OK) exit_code = WARNING;
  1647.         return ERROR;
  1648.     }
  1649.     }
  1650.  
  1651. #else
  1652.     if (!force) {
  1653.     sprintf(strerr, " %s already exists; do you wish to overwrite ?", ofname);
  1654.  
  1655.     if (Cask(strerr)==cancel) {
  1656.         if (exit_code == OK) exit_code = WARNING;
  1657.         return ERROR;
  1658.     }
  1659.     }
  1660.  
  1661.  
  1662. #endif /*MACOS*/
  1663.  
  1664.     (void) chmod(ofname, 0777);
  1665.     if (unlink(ofname)) {
  1666.     PError(ofname);
  1667.     exit_code = ERROR;
  1668.     return ERROR;
  1669.     }
  1670.     return OK;
  1671. }
  1672.  
  1673.  
  1674. #ifndef NO_UTIME
  1675. /* ========================================================================
  1676.  * Set the access and modification times from the given stat buffer.
  1677.  */
  1678. local void reset_times (name, statb)
  1679.     char *name;
  1680.     struct stat *statb;
  1681. {
  1682.     struct utimbuf    timep;
  1683.  
  1684.     /* Copy the time stamp */
  1685.     timep.actime  = statb->st_atime;
  1686.     timep.modtime = statb->st_mtime;
  1687.  
  1688.     /* Some systems (at least OS/2) do not support utime on directories */
  1689.     if (utime(name, &timep) && !S_ISDIR(statb->st_mode)) {
  1690.     if (!quiet) PError(ofname);
  1691.     }
  1692. }
  1693. #endif
  1694.  
  1695.  
  1696. /* ========================================================================
  1697.  * Copy modes, times, ownership from input file to output file.
  1698.  * IN assertion: to_stdout is false.
  1699.  */
  1700. local void copy_stat(ifstat)
  1701.     struct stat *ifstat;
  1702. {
  1703. #ifndef NO_UTIME
  1704.     if (decompress && time_stamp != 0 && ifstat->st_mtime != time_stamp) {
  1705.     ifstat->st_mtime = time_stamp;
  1706.     if (verbose > 1) {
  1707.         fprintf(stderr, "%s: time stamp restored\n", ofname);
  1708.     }
  1709.     }
  1710.     reset_times(ofname, ifstat);
  1711. #endif
  1712.     /* Copy the protection modes */
  1713.     if (chmod(ofname, ifstat->st_mode & 07777)) {
  1714.     if (!quiet) PError(ofname);
  1715.     }
  1716. #ifndef NO_CHOWN
  1717.     chown(ofname, ifstat->st_uid, ifstat->st_gid);  /* Copy ownership */
  1718. #endif
  1719.     remove_ofname = 0;
  1720.     /* It's now safe to remove the input file: */
  1721.     (void) chmod(ifname, 0777);
  1722.     if (unlink(ifname)) {
  1723.     if (!quiet) PError(ifname);
  1724.     }
  1725. }
  1726.  
  1727. #ifndef NO_DIR
  1728.  
  1729. /* ========================================================================
  1730.  * Recurse through the given directory. This code is taken from ncompress.
  1731.  */
  1732. local void treat_dir(dir)
  1733.     char *dir;
  1734. {
  1735.     dir_type *dp;
  1736.     DIR      *dirp;
  1737.     char     nbuf[MAX_PATH_LEN];
  1738.     int      len;
  1739.  
  1740.     dirp = opendir(dir);
  1741.     
  1742.     if (dirp == NULL) {
  1743.     sprintf(strerr, "%s unreadable", dir); Calert(strerr);
  1744.     exit_code = ERROR;
  1745.     return ;
  1746.     }
  1747.     /*
  1748.      ** WARNING: the following algorithm could occasionally cause
  1749.      ** compress to produce error warnings of the form "<filename>.gz
  1750.      ** already has .gz suffix - ignored". This occurs when the
  1751.      ** .gz output file is inserted into the directory below
  1752.      ** readdir's current pointer.
  1753.      ** These warnings are harmless but annoying, so they are suppressed
  1754.      ** with option -r (except when -v is on). An alternative
  1755.      ** to allowing this would be to store the entire directory
  1756.      ** list in memory, then compress the entries in the stored
  1757.      ** list. Given the depth-first recursive algorithm used here,
  1758.      ** this could use up a tremendous amount of memory. I don't
  1759.      ** think it's worth it. -- Dave Mack
  1760.      ** (An other alternative might be two passes to avoid depth-first.)
  1761.      */
  1762.     
  1763.     while ((dp = readdir(dirp)) != NULL) {
  1764.  
  1765.     if (strequ(dp->d_name,".") || strequ(dp->d_name,"..")) {
  1766.         continue;
  1767.     }
  1768.     len = strlen(dir);
  1769.     if (len + NLENGTH(dp) + 1 < MAX_PATH_LEN - 1) {
  1770.         strcpy(nbuf,dir);
  1771.         if (len != 0 /* dir = "" means current dir on Amiga */
  1772. #ifdef PATH_SEP2
  1773.         && dir[len-1] != PATH_SEP2
  1774. #endif
  1775. #ifdef PATH_SEP3
  1776.         && dir[len-1] != PATH_SEP3
  1777. #endif
  1778.         ) {
  1779.         nbuf[len++] = PATH_SEP;
  1780.         }
  1781.         strcpy(nbuf+len, dp->d_name);
  1782.         treat_file(nbuf);
  1783.     } else {
  1784.         sprintf(strerr,"%s/%s: pathname too long\n", dir, dp->d_name);
  1785.         Calert(strerr);
  1786.         exit_code = ERROR;
  1787.     }
  1788.     }
  1789.     closedir(dirp);
  1790. }
  1791. #endif /* ? NO_DIR */
  1792.  
  1793. /* ========================================================================
  1794.  * Free all dynamically allocated variables and exit with the given code.
  1795.  */
  1796. local void do_exit(exitcode)
  1797.     int exitcode;
  1798. {
  1799.     static int in_exit = 0;
  1800.  
  1801.     if (in_exit) exit(exitcode);
  1802.     in_exit = 1;
  1803. /*    if (env != NULL)  free(env),  env  = NULL;*/
  1804. /*    if (args != NULL) free((char*)args), args = NULL;*/
  1805.     FREE(inbuf);
  1806.     FREE(outbuf);
  1807.     FREE(d_buf);
  1808.     FREE(window);
  1809. #ifndef MAXSEG_64K
  1810.     FREE(tab_prefix);
  1811. #else
  1812.     FREE(tab_prefix0);
  1813.     FREE(tab_prefix1);
  1814. #endif
  1815. #ifdef MACOS
  1816.      ReleaseAnimatedCursors(kCalCursorRes);
  1817.      ReleaseMovableModal();
  1818. #endif
  1819.     if (exitcode==0)
  1820.     {
  1821.         in_exit = 0;
  1822.         return;
  1823.     }
  1824.     else
  1825.         exit(exitcode);
  1826. }
  1827.  
  1828. /* ========================================================================
  1829.  * Signal and error handler.
  1830.  */
  1831. RETSIGTYPE abort_gzip()
  1832. {
  1833.    if (remove_ofname) {
  1834.        close(ofd);
  1835.        unlink (ofname);
  1836.    }
  1837.    do_exit(ERROR);
  1838. }
  1839.  
  1840. /*________________________________________________________________________
  1841.  *
  1842.  *         INIT THE OPTIONS
  1843.  */
  1844.  
  1845. local void init_globals( void )
  1846. {
  1847. struct option init_longopts[] =
  1848. {
  1849.  /* { name  has_arg  *flag  val } */
  1850.     {"ascii",      0, 0, 'a'}, /* ascii text mode */
  1851.     {"to-stdout",  0, 0, 'c'}, /* write output on standard output */
  1852.     {"stdout",     0, 0, 'c'}, /* write output on standard output */
  1853.     {"decompress", 0, 0, 'd'}, /* decompress */
  1854.     {"uncompress", 0, 0, 'd'}, /* decompress */
  1855.  /* {"encrypt",    0, 0, 'e'},    encrypt */
  1856.     {"force",      0, 0, 'f'}, /* force overwrite of output file */
  1857.     {"help",       0, 0, 'h'}, /* give help */
  1858.  /* {"pkzip",      0, 0, 'k'},    force output in pkzip format */
  1859.     {"list",       0, 0, 'l'}, /* list .gz file contents */
  1860.     {"license",    0, 0, 'L'}, /* display software license */
  1861.     {"no-name",    0, 0, 'n'}, /* don't save or restore original name & time */
  1862.     {"name",       0, 0, 'N'}, /* save or restore original name & time */
  1863.     {"quiet",      0, 0, 'q'}, /* quiet mode */
  1864.     {"silent",     0, 0, 'q'}, /* quiet mode */
  1865.     {"recursive",  0, 0, 'r'}, /* recurse through directories */
  1866.     {"suffix",     1, 0, 'S'}, /* use given suffix instead of .gz */
  1867.     {"test",       0, 0, 't'}, /* test compressed file integrity */
  1868.     {"no-time",    0, 0, 'T'}, /* don't save or restore the time stamp */
  1869.     {"verbose",    0, 0, 'v'}, /* verbose mode */
  1870.     {"version",    0, 0, 'V'}, /* display version number */
  1871.     {"fast",       0, 0, '1'}, /* compress faster */
  1872.     {"best",       0, 0, '9'}, /* compress better */
  1873.     {"lzw",        0, 0, 'Z'}, /* make output compatible with old compress */
  1874.     {"bits",       1, 0, 'b'}, /* max number of bits per code (implies -Z) */
  1875.     { 0, 0, 0, 0 }
  1876. };
  1877.     *optarg = 0;
  1878.     optind = 0;
  1879.     
  1880.     ascii = 0;        /* convert end-of-lines to local OS conventions */
  1881.     to_stdout = 0;    /* output to stdout (-c) */
  1882.     decompress = 0;   /* decompress (-d) */
  1883.     force = 0;        /* don't ask questions, compress links (-f) */
  1884.     no_name = -1;     /* don't save or restore the original file name */
  1885.     no_time = -1;     /* don't save or restore the original file time */
  1886.     recursive = 0;    /* recurse through directories (-r) */
  1887.     list = 0;         /* list the file contents (-l) */
  1888.     verbose = 0;      /* be verbose (-v) */
  1889.     quiet = 0;        /* be very quiet (-q) */
  1890.     do_lzw = 0;       /* generate output compatible with old compress (-Z) */
  1891.     test = 0;         /* test .gz file integrity */
  1892.     maxbits = BITS;   /* max bits per code for LZW */
  1893.     method = DEFLATED;/* compression method */
  1894.     level = 6;        /* compression level */
  1895.     exit_code = OK;   /* program exit code */
  1896.  
  1897.     total_in = 0;         /* input bytes for all files */
  1898.     total_out = 0;        /* output bytes for all files */
  1899.     remove_ofname = 0;       /* remove output file on error */
  1900.  
  1901.  
  1902.     memcpy(longopts,init_longopts,sizeof(init_longopts));
  1903.     
  1904.     work = zip;
  1905.  
  1906. }